<template>
  <div class="contest-exam-page">
    <!-- 顶部导航栏 -->
    <div class="exam-header">
      <div class="header-left">
        <button @click="goBack" class="back-btn">← 返回比赛列表</button>
        <h1 class="contest-name">{{ contestData.name || contestData.title }}</h1>
      </div>
      <div class="header-right">
        <div class="timer">⏱️ {{ displayTime }}</div>
        <button @click="submitContestResult" class="submit-btn" :disabled="isSubmitting">
          <i class="icon">📤</i>
          {{ isSubmitting ? '提交中...' : '提交比赛' }}
        </button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="exam-content">
      <!-- 左侧：题目列表导航 -->
      <div class="question-nav">
        <h3>题目列表</h3>
        <div class="question-buttons">
          <button
            v-for="(question, index) in questions"
            :key="question.id"
            :class="['question-btn', { active: currentQuestionIndex === index }]"
            @click="selectQuestion(index)"
          >
            {{ String.fromCharCode(65 + index) }}
          </button>
        </div>
      </div>

      <!-- 右侧：所有题目详情（全部显示） -->
      <div class="question-content">
        <div v-if="questions.length === 0" class="no-question">
          <i class="icon">📝</i>
          <p>加载题目中...</p>
        </div>

        <!-- 🔥 遍历显示所有题目，每个题目都有独立的编辑器 -->
        <div v-for="(question, index) in questions" :key="question.id || question.testQuestionId" class="question-detail">
          <!-- 题目标题 -->
          <div class="question-header" :class="{ 'active': currentQuestionIndex === index }">
            <h2>#{{ String.fromCharCode(65 + index) }}. {{ question.title || question.questionName }}</h2>
            <div class="question-meta">
              <span class="meta-tag">📊 传统题</span>
              <span class="meta-tag">⏱️ {{ question.timeLimit }}ms</span>
              <span class="meta-tag">💾 {{ formatMemory(question.spaceLimit) }}</span>
            </div>
          </div>

          <!-- 题目描述 -->
          <div class="section" v-if="question.description || question.questionDescribe">
            <h3>题目描述</h3>
            <div class="content">{{ question.description || question.questionDescribe || '暂无描述' }}</div>
          </div>

          <!-- 输入格式 -->
          <div class="section" v-if="question.inputFormat && question.inputFormat.trim()">
            <h3>📥 输入格式</h3>
            <div class="content">{{ question.inputFormat }}</div>
          </div>

          <!-- 输出格式 -->
          <div class="section" v-if="(question.outputFormat && question.outputFormat.trim()) || question.outputFile">
            <h3>📤 输出格式</h3>
            <!-- 文本格式 -->
            <div v-if="question.outputType === 'text' && question.outputFormat" class="content">
              {{ question.outputFormat }}
            </div>
            <!-- 图片格式 -->
            <div v-else-if="question.outputType === 'local' || question.outputFile" class="output-image">
              <img :src="getImageUrl(question.outputFile || question.outputFormat)" alt="输出格式图片" @error="handleImageError">
            </div>
          </div>

          <!-- 参考程序结果图 -->
          <div class="section" v-if="question.questionPicture">
            <h3>🖼️ 参考程序结果图</h3>
            <div class="content">
              <img :src="getImageUrl(question.questionPicture)" alt="参考程序结果" class="reference-image" @error="handleImageError">
            </div>
          </div>

          <!-- 数据范围和提示 -->
          <div class="section" v-if="question.rangeAndPrompt && question.rangeAndPrompt.trim()">
            <h3>💡 数据范围和提示</h3>
            <div class="content">{{ question.rangeAndPrompt }}</div>
          </div>

          <!-- 测试用例显示 -->
          <div v-if="question.testCases && Array.isArray(question.testCases) && question.testCases.length > 0" class="question-test-cases">
            <h4>🧪 测试用例</h4>
            <div class="test-cases-grid">
              <div v-for="(testCase, tcIndex) in question.testCases" 
                   :key="'tc-' + tcIndex" 
                   class="test-case-card">
                <div class="test-case-header-small">
                  <span>测试用例 {{ tcIndex + 1 }}</span>
                </div>
                <div class="test-case-body">
                  <div class="test-case-field">
                    <label>输入</label>
                    <div class="field-content">{{ testCase.input || '无输入' }}</div>
                  </div>
                  <div class="test-case-field">
                    <label>输出</label>
                    <!-- 如果输出是图片URL，显示图片 -->
                    <div v-if="isImageUrl(testCase.expectedOutput || testCase.output)" class="field-image">
                      <img :src="getImageUrl(testCase.expectedOutput || testCase.output)" alt="输出格式图片" @error="handleImageError">
                    </div>
                    <!-- 否则显示文本 -->
                    <div v-else class="field-content">{{ testCase.expectedOutput || testCase.output || '无输出' }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 在线编译器区域 -->
          <div class="question-editor-section">
            <div class="editor-toggle-header">
              <h4>💻 在线编译器</h4>
              <button @click="toggleEditor(index)" class="toggle-editor-btn">
                <span v-if="showEditor[index]">📤 收起编译器</span>
                <span v-else>📥 打开编译器</span>
              </button>
            </div>
            <div v-show="showEditor[index]" class="editor-container">
              <!-- 🔥 为每个题目添加唯一的 key，确保编辑器独立 -->
              <GocJudge 
                v-if="showEditor[index]"
                :key="'judge-' + (question.id || question.testQuestionId)"
                :problem="getQuestionWithDetails(question, index)"
                :judgeMode="'strict'"
                :enableImageComparison="true"
                @judge-complete="(result) => onJudgeComplete(result, question)"
                @code-submit="(code) => onCodeSubmit(code, question)"
                @error="onEditorError"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import GocJudge from '@/components/GocJudge.vue'
import logger from '../utils/logger.js'
import { getContestDetail, submitContestResult } from '@/api/contest'
import { buildImageURL } from '@/config/api-config'

export default {
  name: 'ContestExam',
  components: {
    GocJudge
  },
  data() {
    return {
      contestId: null,
      contestData: {},
      questions: [],
      currentQuestionIndex: null,
      currentQuestion: null,
      startTime: null,
      displayTime: '00:00:00',
      timerInterval: null,
      showEditor: {},  // 存储每个题目的编译器显示状态
      questionDetails: {},  // 存储每个题目的详细信息
      questionScores: {},  // 存储每道题的得分情况
      isSubmitting: false,  // 提交比赛的加载状态
      totalElapsedTime: 0  // 总耗时（毫秒）
    }
  },
  
  mounted() {
    logger.log('📝 [ContestExam] 比赛做题页面已加载')
    this.contestId = this.$route.params.id
    logger.log('🆔 [ContestExam] 比赛ID:', this.contestId)
    
    // 启动计时器
    this.startTime = Date.now()
    this.timerInterval = setInterval(() => {
      this.updateDisplayTime()
    }, 1000)
    
    this.loadContestData()
  },
  
  beforeUnmount() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval)
      this.timerInterval = null
    }
  },
  
  methods: {
    // 加载比赛数据
    async loadContestData() {
      try {
        logger.log('📥 [ContestExam] 开始加载比赛数据')
        
        const response = await getContestDetail(this.contestId)
        
        logger.log('✅ [ContestExam] API响应:', response)
        
        if (response && response.code === 0 && response.data) {
          this.contestData = response.data
          logger.log('📦 [ContestExam] 比赛数据:', this.contestData)
          
          // 加载题目列表
          if (this.contestData.questions && Array.isArray(this.contestData.questions)) {
            // 为每个题目加载详细信息
            await this.loadQuestionsDetail()
          } else {
            logger.warn('⚠️ [ContestExam] 比赛没有题目')
          }
        } else {
          logger.error('❌ [ContestExam] 加载比赛数据失败')
          alert('加载比赛数据失败')
          this.goBack()
        }
      } catch (error) {
        logger.error('❌ [ContestExam] 加载比赛数据失败:', error)
        alert('加载比赛数据失败')
        this.goBack()
      }
    },
    
    // 加载所有题目的详细信息
    async loadQuestionsDetail() {
      logger.log('📚 [ContestExam] 开始加载题目详情')
      
      const api = await import('@/api/config')
      
      for (let i = 0; i < this.contestData.questions.length; i++) {
        const basicQuestion = this.contestData.questions[i]
        const questionId = basicQuestion.testQuestionId || basicQuestion.id
        
        logger.log(`📥 [ContestExam] 加载第${i+1}题，ID:`, questionId)
        
        try {
          // 调用查看试题详情接口
          const response = await api.default.get('/goc/testQuestion/findById', {
            params: { id: questionId }
          })
          
          if (response && response.code === 0 && response.data) {
            // 🔥 解析 testCases 字段（从JSON字符串转为数组）
            let parsedTestCases = []
            if (response.data.testCases) {
              parsedTestCases = this.parseTestCases(response.data.testCases)
              logger.log(`🧪 [ContestExam] 第${i+1}题测试用例解析:`, parsedTestCases)
            }
            
            const detailedQuestion = {
              ...basicQuestion,
              ...response.data,
              testCases: parsedTestCases,  // 🔥 使用解析后的测试用例数组
              score: basicQuestion.score,
              sortOrder: basicQuestion.sortOrder,
              // 统一字段名
              title: response.data.questionName || response.data.title,
              description: response.data.questionDescribe || response.data.description
            }
            this.questions.push(detailedQuestion)
            logger.log(`✅ [ContestExam] 第${i+1}题加载成功，测试用例数量:`, parsedTestCases.length)
          } else {
            logger.warn(`⚠️ [ContestExam] 第${i+1}题加载失败，使用基础信息`)
            this.questions.push(basicQuestion)
          }
        } catch (error) {
          logger.error(`❌ [ContestExam] 第${i+1}题加载失败:`, error)
          this.questions.push(basicQuestion)
        }
      }
      
      logger.log('✅ [ContestExam] 所有题目加载完成，共', this.questions.length, '题')
      logger.log('📋 [ContestExam] 题目列表详情:', this.questions)
      
      // 默认选择第一题
      if (this.questions.length > 0) {
        this.selectQuestion(0)
        
        // 🔥 自动打开所有题目的编译器
        logger.log('🚀 [ContestExam] 自动打开所有题目的编译器...')
        this.questions.forEach((question, index) => {
          this.showEditor[index] = true
          logger.log(`✅ [ContestExam] 题目${index + 1}编译器已自动打开`)
        })
        
        // 强制更新视图
        this.$forceUpdate()
      } else {
        logger.warn('⚠️ [ContestExam] 没有题目可选择')
      }
    },
    
    // 选择题目
    selectQuestion(index) {
      logger.log('📝 [ContestExam] 选择题目索引:', index)
      this.currentQuestionIndex = index
      this.currentQuestion = this.questions[index]
      logger.log('📋 [ContestExam] 当前题目完整数据:', this.currentQuestion)
      
      // 🔥 滚动到对应题目位置
      this.$nextTick(() => {
        const questionElements = document.querySelectorAll('.question-detail')
        if (questionElements[index]) {
          questionElements[index].scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start'
          })
        }
      })
    },
    
    // 切换编译器显示
    toggleEditor(index) {
      try {
        // 确保 questionDetails 对象存在
        if (!this.questionDetails) {
          this.questionDetails = {}
        }
        
        // 切换指定题目的编译器显示状态
        this.showEditor[index] = !this.showEditor[index]
        logger.log(`💻 [ContestExam] 切换题目 ${index + 1} 的编译器显示状态:`, this.showEditor[index])
        
        // 强制更新视图
        this.$forceUpdate()
      } catch (error) {
        logger.error('❌ [ContestExam] toggleEditor 发生错误:', error)
        this.showEditor[index] = false
      }
    },
    
    // 获取题目详情（供编译器使用）
    getQuestionWithDetails(question, index) {
      try {
        // 确保 questionDetails 对象存在
        if (!this.questionDetails) {
          this.questionDetails = {}
        }
        
        // 优先使用 questionDetails 中的详细信息，如果没有则使用基础题目信息
        const detailedQuestion = this.questionDetails[index] || question
        
        // 🔥 格式化题目数据，确保所有字段都正确
        const formattedQuestion = {
          ...detailedQuestion,
          // 统一字段名
          id: detailedQuestion.id || detailedQuestion.testQuestionId,
          title: detailedQuestion.title || detailedQuestion.questionName || '未命名题目',
          description: detailedQuestion.description || detailedQuestion.questionDescribe || '',
          // 解析 testCases JSON 字符串
          testCases: this.parseTestCases(detailedQuestion.testCases || detailedQuestion.testCaseList),
          // 确保时间和空间限制有默认值
          timeLimit: detailedQuestion.timeLimit || 1000,
          spaceLimit: detailedQuestion.spaceLimit || detailedQuestion.spaceLimitation || 268435456,
          memoryLimit: detailedQuestion.memoryLimit || 128
        }
        
        return formattedQuestion
      } catch (error) {
        logger.error('❌ [ContestExam] getQuestionWithDetails 出错:', error)
        return question
      }
    },
    
    // 🔥 解析测试用例
    parseTestCases(testCasesData) {
      try {
        // 移除频繁的日志输出，避免刷屏
        
        // 如果是字符串，尝试解析JSON
        if (typeof testCasesData === 'string' && testCasesData.trim()) {
          const parsed = JSON.parse(testCasesData)
          
          // 确保返回数组
          const testCasesArray = Array.isArray(parsed) ? parsed : [parsed]
          
          // 🔥 格式化每个测试用例，将 output 映射为 expectedOutput
          const formatted = testCasesArray.map((tc) => {
            return {
              input: tc.input || tc.inputData || '无输入',
              expectedOutput: tc.expectedOutput || tc.output || tc.outputData || tc.expected || '',
              output: tc.output || tc.expectedOutput || '', // 保留原始字段
              expectedTrace: tc.expectedTrace || tc.trace || tc.traceData || [],
              score: tc.score || tc.point || 0
            }
          })
          
          return formatted
        }
        
        // 如果已经是数组，格式化后返回
        if (Array.isArray(testCasesData)) {
          const formatted = testCasesData.map((tc) => ({
            input: tc.input || tc.inputData || '无输入',
            expectedOutput: tc.expectedOutput || tc.output || tc.outputData || tc.expected || '',
            output: tc.output || tc.expectedOutput || '',
            expectedTrace: tc.expectedTrace || tc.trace || tc.traceData || [],
            score: tc.score || tc.point || 0
          }))
          return formatted
        }
        
        // 其他情况返回空数组
        return []
      } catch (error) {
        logger.error('❌ [ContestExam] testCases 解析失败:', error)
        return []
      }
    },
    
    // 🔥 判断是否是图片URL
    isImageUrl(text) {
      if (!text) return false
      
      // 包含图片文件扩展名
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
      const lowerText = text.toLowerCase()
      
      // 检查是否包含图片扩展名
      const hasImageExtension = imageExtensions.some(ext => lowerText.includes(ext))
      
      // 检查是否是URL格式（http开头或包含特殊格式）
      const isUrl = text.startsWith('http') || 
                    text.startsWith('/api/') || 
                    text.includes('文件上传成功')
      
      const result = hasImageExtension && isUrl
      // 移除日志，避免频繁调用时刷屏
      
      return result
    },
    
    // 判题完成回调
    onJudgeComplete(result, question) {
      logger.log('🚨🚨🚨 [ContestExam] ========== onJudgeComplete 被调用了！ ==========')
      logger.log('✅ [ContestExam] 判题完成:', result)
      logger.log('📋 [ContestExam] 题目信息:', question)
      logger.log('📋 [ContestExam] 题目ID字段检查:')
      logger.log('  - question.id:', question?.id)
      logger.log('  - question.testQuestionId:', question?.testQuestionId)
      logger.log('  - question.questionId:', question?.questionId)
      
      // 存储判题结果（包括图片对比的得分）
      if (result && question) {
        // 尝试多种ID字段
        const questionId = question.id || question.testQuestionId || question.questionId
        
        if (!questionId) {
          logger.error('❌ [ContestExam] 无法获取题目ID，无法保存得分')
          logger.error('  - question对象:', question)
          return
        }
        
        // 得分可能来自：
        // 1. 图片对比：result.score（后端返回 data.score）
        // 2. 代码判题：result.totalScore
        const score = result.score || result.totalScore || 0
        
        logger.log('🔍 [ContestExam] 得分来源分析:')
        logger.log('  - result.score:', result.score)
        logger.log('  - result.totalScore:', result.totalScore)
        logger.log('  - 最终得分:', score)
        
        // 判断是否是图片对比的结果
        const isImageComparison = Object.prototype.hasOwnProperty.call(result, 'similar')
        
        this.questionScores[questionId] = {
          score: score,
          correctCount: result.correctCount || 0,
          totalQuestions: result.totalQuestions || 0,
          correctRatio: result.correctRatio || 0,
          timeSpent: result.timeSpent || 0,
          isImageComparison: isImageComparison,
          similar: result.similar || null
        }
        
        logger.log('💾 [ContestExam] 保存题目得分:')
        logger.log('  - 题目ID:', questionId)
        logger.log('  - 题目标题:', question.title || question.questionName || '未知')
        logger.log('  - 得分:', score)
        logger.log('  - 判题类型:', isImageComparison ? '图片对比' : '代码判题')
        if (isImageComparison) {
          logger.log('  - 图片相似度:', result.similar ? '✅ 相似' : '❌ 不相似')
        }
        logger.log('  - 保存的完整数据:', this.questionScores[questionId])
        logger.log('💾 [ContestExam] 当前所有题目得分:', this.questionScores)
        logger.log('💾 [ContestExam] questionScores对象的所有key:', Object.keys(this.questionScores))
        
        // 强制更新视图
        this.$forceUpdate()
        
        logger.log('✅ [ContestExam] ========== 判题完成处理结束 ==========')
      } else {
        logger.warn('⚠️ [ContestExam] 判题结果或题目信息缺失')
        logger.warn('  - result:', result)
        logger.warn('  - question:', question)
      }
    },
    
    // 代码提交回调
    onCodeSubmit(code, question) {
      logger.log('📝 [ContestExam] 代码提交:', code)
      logger.log('📋 [ContestExam] 题目信息:', question)
      
      // 🔥 保存该题目的代码（暂不需要，因为代码会在编辑器内部保留）
      // GocJudge 组件会自动保持每个实例的代码独立
    },
    
    // 编译器错误回调
    onEditorError(error) {
      logger.error('❌ [ContestExam] 编译器错误:', error)
    },
    
    // 更新计时器显示
    updateDisplayTime() {
      if (!this.startTime) return
      
      const elapsed = Date.now() - this.startTime
      const hours = Math.floor(elapsed / 3600000)
      const minutes = Math.floor((elapsed % 3600000) / 60000)
      const seconds = Math.floor((elapsed % 60000) / 1000)
      
      this.displayTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
    },
    
    // 格式化内存大小
    formatMemory(bytes) {
      if (!bytes) return '-'
      const mb = Math.floor(bytes / 1048576)
      return `${mb}MiB`
    },
    
    // 获取图片URL
    getImageUrl(imagePath) {
      if (!imagePath) return ''
      const url = buildImageURL(imagePath)
      // 移除日志，避免频繁调用时刷屏
      return url
    },
    
    // 🔥 处理图片加载错误
    handleImageError(event) {
      logger.warn('⚠️ [ContestExam] 图片加载失败:', event.target.src)
      event.target.style.display = 'none'
      const errorMsg = document.createElement('p')
      errorMsg.className = 'image-error'
      errorMsg.textContent = '图片加载失败'
      event.target.parentElement.appendChild(errorMsg)
    },
    
    // 提交比赛成绩
    async submitContestResult() {
      try {
        logger.log('🔍 [ContestExam] ========== 检查提交前的数据状态 ==========')
        logger.log('🔍 [ContestExam] questionScores对象:', this.questionScores)
        logger.log('🔍 [ContestExam] questionScores是否为空:', Object.keys(this.questionScores).length === 0)
        logger.log('🔍 [ContestExam] questions数组:', this.questions)
        logger.log('🔍 [ContestExam] questions数量:', this.questions.length)
        
        // 确认提交
        if (!confirm('确定要提交比赛吗？提交后将无法修改。')) {
          return
        }
        
        this.isSubmitting = true
        logger.log('📤 [ContestExam] 开始提交比赛成绩')
        
        // 计算总耗时（从进入页面到点击提交的时间）
        if (this.startTime) {
          this.totalElapsedTime = Date.now() - this.startTime
          logger.log('⏱️ [ContestExam] 比赛总耗时:', this.totalElapsedTime, 'ms')
        }
        
        // 计算总分和统计信息
        let totalScore = 0
        let correctCount = 0
        
        logger.log('📊 [ContestExam] ========== 开始计算比赛总分 ==========')
        logger.log('📊 [ContestExam] 当前存储的所有得分数据:', this.questionScores)
        
        // 构建每道题的得分数组
        const questionScoresArray = this.questions.map((q, index) => {
          // 尝试多种ID字段匹配
          const questionId = q.id || q.testQuestionId || q.questionId
          const qScore = this.questionScores[questionId] || {}
          const questionScore = parseInt(qScore.score || 0)
          totalScore += questionScore
          
          // 如果得分大于0，视为正确
          if (questionScore > 0) {
            correctCount++
          }
          
          // 详细记录每道题的得分情况
          logger.log(`📝 [ContestExam] 第${index + 1}题`)
          logger.log(`  - 题目ID: ${questionId}`)
          logger.log(`  - 题目标题: ${q.title || q.questionName || '未知'}`)
          logger.log(`  - 从questionScores获取的得分数据:`, qScore)
          logger.log(`  - 最终得分: ${questionScore}`)
          if (qScore.isImageComparison) {
            logger.log(`  - 判题类型: 图片对比`)
            logger.log(`  - 图片相似度: ${qScore.similar ? '✅ 相似' : '❌ 不相似'}`)
          }
          if (questionScore === 0 && !qScore.score) {
            logger.warn(`  ⚠️ 该题未进行判题，得分为0`)
          }
          
          return {
            testQuestionId: parseInt(questionId),
            score: questionScore,
            timeSpent: qScore.timeSpent || 0
          }
        })
        
        // 计算正确率
        const correctRatio = this.questions.length > 0 ? (correctCount / this.questions.length) : 0
        
        logger.log('📊 [ContestExam] ========== 统计信息 ==========')
        logger.log('  - 总分:', totalScore)
        logger.log('  - 总耗时(ms):', this.totalElapsedTime)
        logger.log('  - 题目总数:', this.questions.length)
        logger.log('  - 已判题数:', Object.keys(this.questionScores).length)
        logger.log('  - 正确题数:', correctCount)
        logger.log('  - 正确率:', (correctRatio * 100).toFixed(2) + '%')
        
        // 准备提交数据（根据接口文档）
        const submitData = {
          competitionId: this.contestId,  // 比赛ID（long类型）
          totalScore: parseInt(totalScore),  // 总分（integer类型）
          totalTime: parseInt(this.totalElapsedTime),  // 总耗时（long类型，毫秒）
          submitTime: new Date().toISOString().replace('T', ' ').substring(0, 19),  // 提交时间（string类型）
          questionScores: questionScoresArray  // 题目得分数组
        }
        
        logger.log('📋 [ContestExam] ========== 准备提交比赛 ==========')
        logger.log('📋 [ContestExam] 提交数据结构:', submitData)
        logger.log('📋 [ContestExam] 开始调用API...')
        
        // 调用提交比赛API
        const response = await submitContestResult(submitData)
        
        logger.log('✅ [ContestExam] 比赛成绩提交成功:', response)
        
        // 停止计时器
        if (this.timerInterval) {
          clearInterval(this.timerInterval)
          this.timerInterval = null
          logger.log('⏱️ [ContestExam] 计时器已停止')
        }
        
        if (response && response.code === 0) {
          // 移除成功提示，直接跳转以改善用户体验
          // if (this.$message) {
          //   this.$message.success(`比赛成绩提交成功！总分: ${totalScore}, 总耗时: ${this.displayTime}`)
          // } else {
          //   alert(`✅ 比赛成绩提交成功！\n总分: ${totalScore}\n总耗时: ${this.displayTime}`)
          // }
          
          // 跳转回比赛列表
          setTimeout(() => {
            this.goBack()
          }, 1500)
        } else {
          const errorMsg = response?.message || '提交失败'
          if (this.$message) {
            this.$message.error(errorMsg)
          } else {
            alert('❌ ' + errorMsg)
          }
        }
        
      } catch (error) {
        logger.error('❌ [ContestExam] 提交比赛成绩失败:', error)
        
        const errorMessage = error.response?.data?.message || error.message || '提交失败，请重试'
        if (this.$message) {
          this.$message.error(errorMessage)
        } else {
          alert('❌ ' + errorMessage)
        }
      } finally {
        this.isSubmitting = false
      }
    },
    
    // 返回
    goBack() {
      this.$router.push('/contests')
    }
  }
}
</script>

<style scoped>
.contest-exam-page {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.exam-header {
  background: white;
  padding: 15px 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-btn {
  padding: 8px 16px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: #5a6268;
}

.contest-name {
  font-size: 1.3em;
  margin: 0;
  color: #2c3e50;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.timer {
  font-size: 1.2em;
  font-weight: 700;
  color: #667eea;
  font-family: 'Courier New', monospace;
}

.submit-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  display: flex;
  align-items: center;
  gap: 6px;
}

.submit-btn .icon {
  font-size: 16px;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

.submit-btn:active:not(:disabled) {
  transform: translateY(0);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 主要内容区域 */
.exam-content {
  flex: 1;
  display: flex;
  gap: 20px;
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
  width: 100%;
}

/* 左侧题目导航 */
.question-nav {
  width: 200px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  height: fit-content;
  position: sticky;
  top: 90px;
}

.question-nav h3 {
  margin: 0 0 15px 0;
  font-size: 1.1em;
  color: #2c3e50;
  font-weight: 600;
}

.question-buttons {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.question-btn {
  padding: 12px;
  background: #f8f9fa;
  border: 2px solid #dee2e6;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  color: #495057;
  transition: all 0.3s ease;
}

.question-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.question-btn.active {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border-color: #667eea;
  transform: scale(1.05);
}

/* 右侧题目内容 */
.question-content {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  /* 🔥 移除内部滚动，使用页面自带滚动条 */
  overflow-y: visible;
  /* 移除高度限制，让内容自然扩展 */
}

.no-question {
  text-align: center;
  padding: 100px 20px;
  color: #7f8c8d;
}

.no-question .icon {
  font-size: 80px;
  margin-bottom: 20px;
  display: block;
}

.no-question p {
  font-size: 18px;
  margin: 0;
}

/* 题目详情 */
/* 🔥 题目容器 - 每个题目之间有间距 */
.question-detail {
  margin-bottom: 40px;
  padding: 25px;
  background: white;
  border-radius: 12px;
  border: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

.question-detail:last-child {
  margin-bottom: 0;
}

.question-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

/* 🔥 当前选中的题目高亮显示 */
.question-header.active {
  border-bottom-color: #667eea;
  background: linear-gradient(to right, rgba(102, 126, 234, 0.05), transparent);
  padding: 10px;
  margin-left: -10px;
  margin-right: -10px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.question-header h2 {
  margin: 0 0 15px 0;
  font-size: 1.5em;
  color: #2c3e50;
  font-weight: 700;
}

.question-header.active h2 {
  color: #667eea;
}

.question-meta {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.meta-tag {
  padding: 6px 12px;
  background: #e9ecef;
  border-radius: 6px;
  font-size: 13px;
  color: #495057;
  font-weight: 500;
}

.section {
  margin-bottom: 30px;
}

.section h3 {
  margin: 0 0 15px 0;
  font-size: 1.2em;
  color: #667eea;
  font-weight: 600;
}

.section .content {
  padding: 15px 20px;
  background: #f8f9fa;
  border-left: 4px solid #667eea;
  border-radius: 6px;
  line-height: 1.8;
  white-space: pre-wrap;
  color: #2c3e50;
}

.output-image,
.reference-image {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.output-image img {
  max-width: 100%;
  height: auto;
  display: block;
}

/* 🔥 参考程序结果图 - 缩小尺寸 */
.reference-image {
  max-width: 500px;  /* 限制最大宽度 */
  max-height: 400px; /* 限制最大高度 */
  height: auto;
  display: block;
  margin: 0 auto;    /* 居中显示 */
  object-fit: contain; /* 保持比例 */
}

/* 图片加载错误提示 */
.image-error {
  color: #f56c6c;
  font-size: 14px;
  padding: 10px;
  background: #fef0f0;
  border-radius: 4px;
  text-align: center;
  margin-top: 10px;
}

/* 测试用例样式 */
.question-test-cases {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.question-test-cases h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.test-cases-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.test-case-card {
  border: 2px solid #e9ecef;
  border-radius: 12px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.test-case-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.test-case-header-small {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 12px 18px;
  text-align: center;
  font-weight: 600;
  font-size: 15px;
}

.test-case-body {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.test-case-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.test-case-field label {
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  letter-spacing: 0.3px;
}

.test-case-field .field-content {
  background: #f8f9fa;
  padding: 15px 18px;
  border-radius: 8px;
  border: 2px solid #e9ecef;
  font-family: 'Courier New', monospace;
  font-size: 16px;
  color: #2c3e50;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.8;
  min-height: 60px;
}

.test-case-field .field-image {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid #e9ecef;
}

.test-case-field .field-image img {
  max-width: 100%;
  max-height: 350px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
}

.test-case-field .field-image img:hover {
  transform: scale(1.05);
  cursor: zoom-in;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}

/* 在线编译器区域 */
.question-editor-section {
  margin-top: 30px;
  padding-top: 30px;
  border-top: 2px solid #e9ecef;
}

.editor-toggle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.editor-toggle-header h4 {
  margin: 0;
  font-size: 1.2em;
  color: #667eea;
  font-weight: 600;
}

.toggle-editor-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.toggle-editor-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.editor-container {
  margin-top: 15px;
  border-radius: 12px;
  overflow: visible; /* 🔥 改为 visible，让编译器自然扩展 */
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .exam-content {
    flex-direction: column;
  }
  
  .question-nav {
    width: 100%;
    position: static;
  }
  
  .question-buttons {
    grid-template-columns: repeat(6, 1fr);
  }
}

@media (max-width: 768px) {
  .exam-header {
    flex-direction: column;
    gap: 10px;
    padding: 15px;
  }
  
  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-right {
    width: 100%;
    flex-direction: column;
    gap: 10px;
  }
  
  .timer {
    width: 100%;
    text-align: center;
  }
  
  .submit-btn {
    width: 100%;
    justify-content: center;
  }
  
  .contest-name {
    font-size: 1.1em;
  }
  
  .exam-content {
    padding: 10px;
  }
  
  .question-content {
    padding: 20px;
  }
  
  .question-buttons {
    grid-template-columns: repeat(4, 1fr);
  }
  
  /* 移动端测试用例样式优化 */
  .test-cases-grid {
    grid-template-columns: 1fr;
  }
  
  .test-case-card {
    margin-bottom: 10px;
  }
}
</style>

